package com.liuxu.topnews;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.liuxu.topnews.Manager.BackGroudManager;
import com.liuxu.topnews.bean.App;
import com.liuxu.topnews.utils.RootUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
import static com.liuxu.topnews.MyApplication.appname;
import static com.liuxu.topnews.MyApplication.toast;

public class AccessService extends AccessibilityService {
    public RootUtils Helper = new RootUtils();
    public int search_count=5;
    public boolean choice[];
    public Thread mythread;
    public Uiutil uiutil=new Uiutil();
    public Dialogs dialogs;

    public void onServiceConnected(){
        Log.v("无障碍服务","打开");
        dialogs=new Dialogs();
    }
    public void onCreate() {
        super.onCreate();
        Log.e("Service", "onCreate");

    }

    public void onDestroy() {
        Log.e("Service", "onDestroy");
        super.onDestroy();

    }
    @Override
    public boolean onKeyEvent(KeyEvent event) {
        if(MyApplication.permission) {
            int key = event.getKeyCode();
            switch (key) {
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    showtoast("暂停运行",true);
                    MyApplication.Pause=true;
                    break;
                case KeyEvent.KEYCODE_VOLUME_UP:
                    showtoast("继续运行",true);
                    MyApplication.Pause=false;
                    break;
            }
        }
        return super.onKeyEvent(event);
    }
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int type = event.getEventType();
        if (event.getClassName() != null) {
            String classname = event.getClassName().toString();
            if (type==TYPE_WINDOW_STATE_CHANGED) {
                MyApplication.UpClassName = MyApplication.NowClassName;
                MyApplication.NowClassName = classname;
                Log.v("nowclassname==" + MyApplication.NowClassName, "窗口变动");
                try {
                    Object text=dialogs.dialogs.get(classname);
                    if (text!=null) {
                        Helper.ClickNodes(uiutil.findNodesByText(text.toString()));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            }
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        String hour= String.valueOf(cal.get(Calendar.HOUR));
        String minute = String.valueOf(cal.get(Calendar.MINUTE ));
        String second  = String.valueOf(cal.get(Calendar.SECOND ));
//        Log.i("现在时间", hour+"时"+minute+"分"+second+"秒");
        if (cal.get(Calendar.AM_PM) ==0&&MyApplication.sleep){
            if (hour.equals("1")&&!MyApplication.Pause){
                    Log.i("时间到", "暂停");
                    MyApplication.Pause=true;
                    showtoast("凌晨开始休息",true);
            }
            if (hour.equals("5")&&MyApplication.Pause){
                    Log.i("时间到", "继续");
                    MyApplication.Pause=false;
                    showtoast("起床开始赚钱",true);
            }
        }
    }
    public int onStartCommand(Intent intent, int flags, int startId) {
            Log.e("Service", "onStartCommand");
            choice = intent.getBooleanArrayExtra("choices");
            mythread=new Thread(new Runnable() {
            @Override
            public void run() {
                Read reader = new Read();
                Uiutil Finder = new Uiutil();
                DisplayMetrics dm = getResources().getDisplayMetrics();
                Helper.setScreenWidth(dm.widthPixels);
                Helper.setScreenHeight(dm.heightPixels);
                String[] appnames = AppInfo.appnames;
                while (MyApplication.permission) {
                    Log.v("我在运行", "我是无障碍");
                    for (int i = 0; i < choice.length; i++) {
                        if (choice[i]) {
                            try {
                                try {
                                    appname=getappinfo(appnames[i],0);
                                    MyApplication.packname=getappinfo(appnames[i],1);
                                    MyApplication.mainname=getappinfo(appnames[i],2);
                                    MyApplication.newsname=getappinfo(appnames[i],3);
                                    reader.app=(App) reader.read_setting.get(appname);
//                                    Log.v("app", reader.app.toString());
                                } catch (NoSuchFieldException e) {
                                    e.printStackTrace();
                                }
                                reader.getClass().getDeclaredMethod(appnames[i], RootUtils.class, Uiutil.class).invoke(reader, Helper, Finder);
                                Finder.clickTextViewByText("确定");
                                Finder.clickTextViewByText("取消");
                                new BackGroudManager().clean();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                            }
                        } else {
                        }
                    }
                }
                Log.v("运行完毕","完毕");
            }
        });
            mythread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    public void onInterrupt() {
    }
    public String getappinfo(String name,int index) throws NoSuchFieldException, IllegalAccessException {
        Field field = AppInfo.class.getDeclaredField(name);
        field.setAccessible(true);
        String[] result=(String[])field.get(new AppInfo());
        return (result[index]);
    }
    class Uiutil {
        public List<AccessibilityNodeInfo> findNodesByText(String text) throws InterruptedException {
            List<AccessibilityNodeInfo> result = new ArrayList<>();
//                List<AccessibilityWindowInfo> windowInfos =getWindows();
            int time=search_count;
            Log.v("按照文字查找",text);
            while (result.size() == 0&&time>0){
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                if (nodeInfo != null) {
                    Log.v("有控件，找",text);
                    result=nodeInfo.findAccessibilityNodeInfosByText(text);
                }
                Thread.sleep(1000);
                time-=1;
            }
            return result;
        }
        public List<AccessibilityNodeInfo> findNodesById(String viewId) throws InterruptedException {
            List<AccessibilityNodeInfo> result = new ArrayList<>();
            int time=search_count;
            Log.v("按照控件查找",viewId);
            while (result.size() == 0&&time>0){
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                if (nodeInfo != null) {
                    Log.v("有控件，找",viewId);
                    result=nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
                }
                Thread.sleep(1000);
                time-=1;
            }
            return result;
        }
        public void set_text(List<AccessibilityNodeInfo> Node,String word) throws Exception {
            if (Node.size() != 0) {
                Bundle arguments = new Bundle();
                arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, word);
                Node.get(0).performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
            }
            else {
                throw new Exception("找不到");
            }
        }
        public void OpenAPP(String var1) {
            if (MyApplication.NowClassName.equals(MyApplication.mainname)) {
                showtoast("阅读下一篇",true);
            } else {
                PackageManager var2 = AccessService.this.getPackageManager();
                new Intent();
                Intent var3 = var2.getLaunchIntentForPackage(var1);
                AccessService.this.startActivity(var3);
                try {
                    Thread.sleep(7000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }



        /**
         * 模拟点击事件
         *
         * @param nodeInfo nodeInfo
         */
        public void performViewClick(AccessibilityNodeInfo nodeInfo) {
            if (nodeInfo == null) {
                return;
            }
            while (nodeInfo != null) {
                if (nodeInfo.isClickable()) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    break;
                }
                nodeInfo = nodeInfo.getParent();
            }
        }

        /**
         * 模拟返回操作
         */
        public void performBackClick() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","返回");
            performGlobalAction(GLOBAL_ACTION_BACK);
        }

        /**
         * 模拟下滑操作
         */
        public void performScrollBackward() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","下滑");
            performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
        }

        /**
         * 模拟上滑操作
         */
        public void performScrollForward() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","上滑");
            performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        }

        /**
         * 查找对应文本的View
         *
         * @param text text
         * @return View
         */
        public AccessibilityNodeInfo findViewByText(String text) {
            return findViewByText(text, false);
        }

        /**
         * 查找对应文本的View
         *
         * @param text      text
         * @param clickable 该View是否可以点击
         * @return View
         */
        public AccessibilityNodeInfo findViewByText(String text, boolean clickable) {
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return null;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null && (nodeInfo.isClickable() == clickable)) {
                        return nodeInfo;
                    }
                }
            }
            return null;
        }

        /**
         * 查找对应ID的View
         *
         * @param id id
         * @return View
         */
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
        public AccessibilityNodeInfo findViewByID(String id) {
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return null;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null) {
                        return nodeInfo;
                    }
                }
            }
            return null;
        }

        public boolean clickTextViewByText(String text) {
            Log.v("按照文字查找",text);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return false;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null) {
                        Log.v("点击：",text);
                        performViewClick(nodeInfo);
                        return true;
                    }
                }
            }
            return false;
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void clickTextViewByID(String id) {
            Log.v("按照ID查找",id);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null) {
                        Log.v("点击：",id);
                        performViewClick(nodeInfo);
                        break;
                    }
                }
            }
        }
        public void  clickTextViewByDesc(String desc) throws InterruptedException {
            Log.v("按照Desc查找",desc);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            AccessibilityNodeInfo Nodes = getRootInActiveWindow();
            if (Nodes == null) {
                return;
            }else {
                findTextViewByDesc(Nodes,desc);
            }



        }
        public void findTextViewByDesc(AccessibilityNodeInfo Nodes,String desc) throws InterruptedException {
            Log.v("查找增加","一层");
            for (int i=0;i<Nodes.getChildCount();i++){
                AccessibilityNodeInfo Node=Nodes.getChild(i);
                if (Node==null){
                    Log.v("此对象","为空");
                }else {
                    if(Node.getContentDescription()==null||!Node.getContentDescription().toString().equals(desc)){
                        if (Node.getChildCount()>0) {
                            findTextViewByDesc(Node, desc);
                        }
                    }else {
                        Log.v("找到目标",Node.getContentDescription().toString());
                        Helper.ClickNode(Node);
                        break;
                    }
                }
            }
        }

        public boolean FindContentDesc(AccessibilityNodeInfo var1, String var2) {
            if (var1 != null) {
                for(int var3 = 0; var3 < var1.getChildCount(); ++var3) {
                    if (var1.getChild(var3) != null) {
                        if (!var1.getChild(var3).isClickable()) {
                            if (var1.getChild(var3).getChildCount() > 0) {
                                if (var1.getChild(var3) == null) {
                                    break;
                                }

                                this.FindContentDesc(var1.getChild(var3), var2);
                            }
                        } else if (var1.getChild(var3).getContentDescription() != null && var1.getChild(var3).getContentDescription().toString().equals(var2)) {

                            return true;
                        }
                    }
                }
            }

            return false;
        }

        /**
         * 模拟输入
         *
         * @param nodeInfo nodeInfo
         * @param text     text
         */
        public void inputText(AccessibilityNodeInfo nodeInfo, String text) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Bundle arguments = new Bundle();
                arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("label", text);
                clipboard.setPrimaryClip(clip);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
            }
        }
    }
    public void showtoast(final String text, final boolean now){
        Handler handlerThree=new Handler(
                Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                if (now) {
                    toast.setText(text);
                    toast.show();
                } else {
                    Toast.makeText(MyApplication.getContext(),text,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

